﻿using Google.Protobuf;

namespace Pisces
{
	/**
	 * 网络模块
     * created by wangqiang
    **/
	public class NetworkModule : AbstractSingletonModule<NetworkModule>, InterfaceEntityLiftcycle
	{
		/// <summary>
		/// 网关的tcp链接通道
		/// 消息结构： [消息头][消息体]
		/// </summary>
		private TcpChannel gatewayChannel;

		/// <summary>
		/// 当前支持ip v4
		/// </summary>
		/// <param name="ip"></param>
		/// <param name="port"></param>
		/// <param name="protocolParser">消息解析器</param>
		public void connectToGateway(string ip, int port, IProtocolParser protocolParser)
		{
			gatewayChannel = new TcpChannel();
			gatewayChannel.onAwake();
			int result = gatewayChannel.connectToGateway(ip, port, protocolParser);
			if (result < 0)
			{
				PiscesLog.error($"链接gateway失败, 错误码{result}");
			}
		}
		
		/// <summary>
		/// 向服务器网关发送tcp消息
		/// </summary>
		/// <param name="packetID"></param>
		/// <param name="packet"> protobuf格式 </param> 
		public void sendTcpPacket(short packetID, IMessage packet)
		{
			if (gatewayChannel != null)
			{
				gatewayChannel.sendProtobufPacket(packetID, packet);
			}
		}

		public override void onUpdate(float deltaTime)
		{
			base.onUpdate(deltaTime);

			if (gatewayChannel != null)
			{
				gatewayChannel.onUpdate(deltaTime);
			}
		}

		public override void onDestroy()
		{
			base.onDestroy();

			if (gatewayChannel != null)
			{
				gatewayChannel.onDestroy();
			}
		}
		
		
	}
}